﻿using Microsoft.AspNetCore.Mvc;
using Serilog.Context;

namespace Yangka.Serilog
{
    public class CorrelationIdMiddleware
    {
        private readonly RequestDelegate _next;
        private const string CorrelationIdHeader = "X-Correlation-Id";

        public CorrelationIdMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 从请求头获取或生成新的Correlation ID
            var correlationId = context.Request.Headers.TryGetValue(CorrelationIdHeader, out var headerId)
                ? headerId.ToString()
                : Guid.NewGuid().ToString();

            // 存储到HttpContext.Items和响应头
            context.Items[CorrelationIdHeader] = correlationId;
            context.Response.Headers.Append(CorrelationIdHeader, correlationId);

            // 将Correlation ID推送到Serilog的LogContext
            using (LogContext.PushProperty(CorrelationIdHeader, correlationId))
            {
                await _next(context);
            }
        }

        
    }
}
